# cf/models.py
from django.db import models
import json


class CFUser(models.Model):
    """Codeforces用户模型"""
    username = models.CharField(max_length=100, unique=True, verbose_name="用户名")
    handle = models.CharField(max_length=100, unique=True, verbose_name="Codeforces句柄")
    is_active = models.BooleanField(default=True, verbose_name="是否监控")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    last_updated = models.DateTimeField(auto_now=True, verbose_name="最后更新")

    class Meta:
        db_table = 'cf_users'
        verbose_name = 'CF用户'
        verbose_name_plural = 'CF用户'

    def __str__(self):
        return f"{self.username} ({self.handle})"


class Submission(models.Model):
    """提交记录模型"""
    user = models.ForeignKey(CFUser, on_delete=models.CASCADE, related_name='submissions', verbose_name="用户")
    submission_id = models.IntegerField()  # 移除了unique约束，因为不同用户可能有相同submission_id
    contest_id = models.IntegerField()  # 比赛ID
    problem_index = models.CharField(max_length=10)  # 题目索引(A/B/C等)
    problem_name = models.CharField(max_length=255)  # 题目名称
    programming_language = models.CharField(max_length=100)  # 编程语言
    verdict = models.CharField(max_length=50)  # 提交结果(AC/WA等)
    creation_time = models.DateTimeField()  # 提交时间
    submission_time = models.CharField(max_length=20)  # 提交时间戳
    tags = models.TextField()  # 题目标签(JSON格式)

    class Meta:
        db_table = 'submissions'
        ordering = ['-creation_time']
        unique_together = ['user', 'submission_id']  # 同一个用户的提交ID是唯一的

    def get_tags_list(self):
        """获取标签列表"""
        return json.loads(self.tags) if self.tags else []

    def __str__(self):
        return f"{self.user.handle} - {self.problem_name} - {self.verdict}"


class DailyStats(models.Model):
    """每日统计模型"""
    user = models.ForeignKey(CFUser, on_delete=models.CASCADE, related_name='daily_stats', verbose_name="用户")
    date = models.DateField()  # 移除了unique约束
    total_submissions = models.IntegerField(default=0)  # 总提交数
    accepted_submissions = models.IntegerField(default=0)  # 通过提交数
    problems_solved = models.IntegerField(default=0)  # 解决问题数
    unique_problems = models.TextField()  # 独特问题列表(JSON格式)

    class Meta:
        db_table = 'daily_stats'
        ordering = ['-date']
        unique_together = ['user', 'date']  # 同一个用户每天只有一条统计记录

    def get_unique_problems_list(self):
        """获取独特问题列表"""
        return json.loads(self.unique_problems) if self.unique_problems else []

    def __str__(self):
        return f"{self.user.handle} - {self.date} - {self.problems_solved}题"